import {
    timeFormat,
    setMonthData,
    setChooseDate,
    setChooseRange,
    clearChooseRange
} from './utils'

var init = false;
var app = getApp();
Component({
    options: {
        multipleSlots: true,
        styleIsolation: 'apply-shared'
    },
    data: {
        monthObj:{},
        valueChoose:[],
        time_now:timeFormat(new Date(),'y/m/d'),
        time_til:'----年--月',
        curtime:'',
        choose_date:{},
        statusHeight:44,
        navHeight:44,
        status_active:false,
        status_show:false,
        btn_disabled:true
    },
    properties:{
        showtype:{
            type:String,
            value:''
        },
        show:{
            type:Boolean,
            value:false
        },
        position:{
            type:String,
            value:'bottom'
        },
        value: {
            type: [String,Array],
            value: '',
            observer:function(newVal, oldVal){
                this.resetChooses(newVal)
            }
        },
        template:{
            type: String,
            value: 'default'
        },
        monthdata:{
            type: Object,
            value:{},
            observer:function(newVal, oldVal){
                // console.log(6,newVal,oldVal)
                // this.loopData(newVal)
            }
        },
        choosetype:{
            type:String,
            value:'date'
        }
    },
    ready:function(){
        var value = this.data.value,
            ct = new Date();
        if(this.data.choosetype=='date'&&value){
            ct = new Date(value);
        }
        if(this.data.choosetype=='dates'||this.data.choosetype=='range'){
            if(value&&value.length){
                ct = new Date(value[0])
            }
        }
        this._initmonth(new Date(ct.getFullYear()+'/'+(ct.getMonth()+1)+'/01'))
        this.setNavheight();
    },
	observers: {
		'show':function(newval){
			if(newval){
				this.setData({status_active:true})
				setTimeout(()=>{
					this.setData({status_show:true})
				},0)
			}else{
				this.setData({status_show:false})
				setTimeout(()=>{
					this.setData({status_active:false})
				},300)
			}
			// console.log(5,newval)
		}
    },
    methods:{
        stopmove(){
            return;
        },
        setNavheight(){
            var sysinfo = app.globalData.window.all
              , statusHeight = sysinfo.statusBarHeight                
              , navheight = sysinfo.system.indexOf('iOS')>-1?44:48;
            this.setData({
              statusHeight:statusHeight,
              navHeight:navheight
            })
        },
        //初始化日历视图
        _initmonth(time){
            let data = setMonthData(time),
                obj = {};

            obj.time_til = timeFormat(time,'y年m月',true)
            obj['monthObj'] = data;
            obj.curtime = time;

            this.setData(obj,()=>{
                if(init){
                    this.resetChoose();
                }
                init = true;
            })

        },
        //前一个月
        _click_prev_month(){
            this.data.curtime.setMonth(this.data.curtime.getMonth()-1);
            this._initmonth(this.data.curtime)
        },
        //后一个月
        _click_next_month(e){
            this.data.curtime.setMonth(this.data.curtime.getMonth()+1);
            this._initmonth(this.data.curtime)
        },
        resetChooses(values){
            var valueChoose = []
            if(this.data.choosetype=='date'){
                valueChoose.push(timeFormat(new Date(values),'y/m/d'))
            }else{
                for(var i=0;i<values.length;i++){
                    valueChoose.push(timeFormat(new Date(values[i]),'y/m/d'))
                }
            }
            this.setData({valueChoose:valueChoose},()=>{
                this.resetChoose();
            })
        },
        //激活选中
        resetChoose(){
            if(!init){
                setTimeout(()=>{
                    this.resetChoose()
                },500)
                return;
            }
            
            var that = this,
                valueChoose = this.data.valueChoose,
                monthObj = this.data.monthObj,
                obj = {},
                type = this.data.choosetype;

            if(type=='date'||type=='dates'){
                valueChoose.forEach((item,index) => {
                    setChooseDate(item,monthObj,obj)
                });
            }
            if(type=='range'&&valueChoose.length==2){
                setChooseRange(valueChoose,monthObj,obj)
            }else if(type=='range'&&valueChoose.length==0){
                clearChooseRange(monthObj,obj)
            }
            
            this.setData(obj,()=>{
                this.checkBtnStatus();
            })
        },
        //日期点击
        dataClick(e){
            let index = e.currentTarget.dataset.index,
                key = e.currentTarget.dataset.key,
                item = e.currentTarget.dataset.item,
                list = this.data.monthObj.list,
                obj = {};
            
            var type = this.data.choosetype;
            if(type=='date'){
                this.triggerEvent('dateclick', {time:new Date(key),format:key,list:item.data});
                for(var i=0;i<list.length;i++){
                    if(list[i].key==key){
                        obj['monthObj.list['+i+'].chooseclass']='td-choose'
                    }
                    if(list[i].chooseclass&&list[i].key!=key){
                        obj['monthObj.list['+i+'].chooseclass']=''
                    }
                }
                this.triggerEvent('close', {});
            }

            if(type=='dates'){
                obj['monthObj.list['+index+'].chooseclass'] = (list[index].chooseclass?'':'td-choose')
            }

            if(type=='range'){
                if(this.data.valueChoose.length==2||this.data.valueChoose.length==0){
                    obj.valueChoose = [key];
                    for(var i=0;i<list.length;i++){
                        if(list[i].key==key){
                            obj['monthObj.list['+i+'].chooseclass']='td-choose'
                        }else{
                            obj['monthObj.list['+i+'].chooseclass']=''
                        }
                    }
                }else if(key!=this.data.valueChoose[0]){
                    this.data.valueChoose.push(key);
                    this.data.valueChoose.sort((a,b)=>{
                        return new Date(a).getTime()-new Date(b).getTime()
                    })
                    obj.valueChoose = this.data.valueChoose;
                    setChooseRange(this.data.valueChoose,this.data.monthObj,obj)
                }
                obj['btn_disabled'] = this.data.valueChoose.length==2?false:true;
            }
            this.setData(obj,()=>{
                this.checkBtnStatus();
            })

        },
        checkBtnStatus(){
            let o ={};
            if(this.data.choosetype=='range'){
                o['btn_disabled'] = this.data.valueChoose.length==2?false:true;
            }
            this.setData(o)
        },
        close(){
            this.triggerEvent('close', {});
        },
        sure(){
            var list = this.data.monthObj.list,
                rs = [];
            for(var i=0;i<list.length;i++){
                if(list[i].chooseclass){
                    rs.push(list[i].key);
                }
            }

            if(this.data.choosetype=='dates'){
                this.triggerEvent('dateschoose', rs);
                this.triggerEvent('close', {});
            }else if(this.data.choosetype=='range'){
                if(this.data.valueChoose.length!=2){
                    wx.showToast({title:'请选择时间范围',icon:'none'})
                }else{
                    this.triggerEvent('daterange', this.data.valueChoose);
                    this.triggerEvent('close', {});
                }
            }
        }
    }
})

